<template>
  <el-form
    :model="formData"
    :rules="rules"
    ref="formRef"
    label-width="100px"
    class="form-container"
  >
    <el-form-item label="壁纸" prop="fileList">
      <ImageUpload v-model:fileList="formData.fileList" ref="imageUploadRef" />
    </el-form-item>
    <el-form-item label="描述" prop="description">
      <el-input v-model="formData.description" type="textarea" placeholder="请输入描述"  show-word-limit  maxlength="500"></el-input>
    </el-form-item>
    <el-form-item label="分类" prop="classId">
      <el-select placeholder="请选择分类" v-model="formData.classId" filterable>
        <el-option
          v-for="item in categoryNames"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="标签" prop="description">
      <el-tag
        v-for="tag in formData.tabs"
        :key="tag"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
      >
        {{ tag }}
      </el-tag>
      <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="input-new-tag"
        size="small"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
      />
      <el-button v-else class="button-new-tag" size="small" @click="showInput">
        增加标签
      </el-button>
    </el-form-item>
  </el-form>
  <div class="button-container">
    <el-button type="primary" @click="submitForm">提交</el-button>
    <el-button @click="resetForm">重置</el-button>
  </div>
</template>

<script setup>
import { reactive, ref, nextTick, onMounted, watch } from 'vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { apiGetCategoryNames } from '@/api/wallpaper/classify'
import { apiPostingWallpaper } from '@/api/wallpaper/posting'
import useUserStore from '@/store/modules/user'

const formData = reactive({
  description: '',
  classId: '',
  fileList: [],
  tabs: [],
})
const wallpaper = ref()

const rules = reactive({
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  classId: [{ required: true, message: '请选择分类', trigger: 'blur' }],
})

const formRef = ref(null)
const imageUploadRef = ref(null)

const userStore = useUserStore()

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await imageUploadRef.value.submitUpload()
      watch(
        () => formData.fileList,
        (newVal) => {
          if (newVal.length > 0) {
            // 更新 wallpaper.value，只包含必要的属性
            wallpaper.value = {
              smallPicurl: newVal[0].url,
              ...pick(formData, ['description', 'tabs']), // pick 函数用于选择特定的属性
            }
            wallpaper.value.userId = userStore.id
            wallpaper.value.nickname = userStore.name
            // 将tabs数组转为字符串
            wallpaper.value.tabs = wallpaper.value.tabs.join(',')
            // 调用 api 上传壁纸
            apiPostingWallpaper(wallpaper.value)
              .then((res) => {
                // console.log(res)
                if (res.code === 200) {
                  // 上传成功，重置表单
                  resetForm()
                }
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            // 如果 fileList 变为空，重置 wallpaper.value
            wallpaper.value = null
          }
        },
        { deep: true, immediate: true }, // 立即执行一次监听器以处理初始值
      )
    } else {
      console.log('error submit', formData)
      return false
    }
  })
}

const resetForm = () => {
  formRef.value.resetFields()
  imageUploadRef.value.resetUpload()
}

const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref()

const handleClose = (tag) => {
  formData.tabs.splice(formData.tabs.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    formData.tabs.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 辅助函数 pick，用于从对象中提取指定的属性
function pick(obj, keys) {
  return keys.reduce((acc, key) => {
    if (obj && Object.prototype.hasOwnProperty.call(obj, key)) {
      acc[key] = obj[key]
    }
    return acc
  }, {})
}

const categoryNames = ref([])

// 获取分类名称
apiGetCategoryNames('1').then((res) => {
  categoryNames.value = res.data
})

// 组件挂载后检查初始状态
onMounted(() => {
  if (formData.fileList.length > 0) {
    wallpaper.value = {
      smallPicurl: formData.fileList[0].url,
      ...pick(formData, ['description', 'tabs']),
    }
  }
})
</script>

<style lang="scss" scoped>
.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.button-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 800px;

  .el-button {
    flex-grow: 1;
    margin: 0 5px;
  }
}
</style>
